const api = require('../../api/api.js');
const app = getApp();

Page({
  data: {
    imgUrl: app.globalData.imgUrl + 'enterpriseImage/',
    enterprises: []
  },
  onLoad() {
    let that = this;
    wx.getStorage({
      key: 'userId',
      success: function(res) {
        let account = res.data;
        wx.getStorage({
          key: 'role',
          success(res) {
            let role = res.data;
            if(role === 0) {
              that.getAllEnterprise()
            } else {
              that.queryEnterprise(account)
            }
          }
        })
      },
    })
  },
  getAllEnterprise() {
    let that = this;
    api.getAllEnterprise({
      data: {
        page: -1,
        limit: -1
      },
      success(res) {
        const enterprises = res.data.enterprise
        enterprises.map(i => {
          if (i.image === '') {
            i.image = that.data.imgUrl + 'defaultLogo.png';
          } else {
            i.image = that.data.imgUrl + i.image;
          }
        });
        that.setData({
          enterprises
        });
      }
    })
  },
  queryEnterprise(account) {
    let that = this;
    api.queryEnterprise({
      data: {
        account,
        page: -1,
        limit: -1
      },
      success(res) {
        console.log(res.data);
        let enterprises = res.data.enterprise;
        enterprises.map(i => {
          if (i.image === '') {
            i.image = that.data.imgUrl + 'defaultLogo.png';
          } else {
            i.image = that.data.imgUrl + i.image;
          }
        });
        that.setData({
          enterprises
        });
      }
    });
  },
  goToEntInfoPage(e) {
    let entId = e.currentTarget.dataset.entid;
    wx.navigateTo({
      url: `/pages/companyinfo/companyinfo?entId=${entId}`,
    })
  },
  goToAddCompanyPage() {
    wx.navigateTo({
      url: `/pages/addcompany/addcompany`,
    })
  }
})